package com.itheima.controller;


import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {

  @Autowired
  private UserService userService;




  @RequestMapping("/login")
  public String login(User user, HttpServletRequest request) {

    if (StringUtils.isEmpty(user.getCaptcha()) || StringUtils.isEmpty(user.getEmail())){
      request.setAttribute("msg", "邮箱或密码和验证码不能为空");
      return "forward:/admin/login.jsp";
    }
    try {
      User u = userService.login(user);
      if (u != null) {
        //在这里判断验证码
        HttpSession session = request.getSession();
        String _captcha = (String) session.getAttribute("captcha");

        if (!_captcha.equals(user.getCaptcha())) {
          request.setAttribute("msg", "验证码错误");

          return "forward:/admin/login.jsp";
        }
        request.getSession().setAttribute("USER_SESSION", u);
        return "redirect:/admin/main.jsp";
      }
      request.setAttribute("msg", "用户名或密码错误");
    } catch (Exception e) {
      e.printStackTrace();
      request.setAttribute("msg", "系统错误");
      return "forward:/admin/login.jsp";
    }
    return null;
  }

  @RequestMapping("/logout")
  public String logout(HttpServletRequest request) {
    try {
      HttpSession session = request.getSession();
      session.invalidate();
      return "forward:/admin/login.jsp";
    } catch (Exception e) {
      e.printStackTrace();
      request.setAttribute("msg", "系统错误");
      return "forward:/admin/login.jsp";
    }
  }
}
